/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.solr.api.client;

import com.pingan.haofang.searchcloud.api.constants.EngineType;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pingan.haofang.searchcloud.api.route.AliasUtils;
import com.pingan.haofang.searchcloud.api.route.IndexAliasRegister;
import com.pingan.haofang.searchcloud.api.route.IndexRoute;

/**
 * @author huhailiang937
 * @date 2017年7月6日下午4:30:59
 * @since 1.0.0
 */

@Component("solrIndexAliasRegister")
public class SolrIndexAliasRegister implements IndexAliasRegister {

    protected static Logger LOG = LoggerFactory.getLogger(SolrIndexAliasRegister.class);

    @Autowired
    private SolrClientFactory solrClientFactory;

    /* (non-Javadoc)
     * @see com.pingan.haofang.searchcloud.api.route.IndexAliasRegister#register(com.pingan.haofang.searchcloud.api.route.IndexRoute)
     */
    @SuppressWarnings("rawtypes")
    @Override
    public boolean register(IndexRoute indexRoute) {
        if (indexRoute.getEngineType() != EngineType.SOLR.getValue()) {
            return false;
        }

        try {
            CloudSolrClient cloudSolrClient = solrClientFactory.getByHost(indexRoute.getEngineHost());
            String aliasName = AliasUtils.convertAliasName(indexRoute.getCollectionRouteKey());
            CollectionAdminRequest createAlias = CollectionAdminRequest.createAlias(aliasName,
                    indexRoute.getCollectionName());
            cloudSolrClient.request(createAlias);
            LOG.info("alias created, collections:{}, alias:{}", indexRoute.getCollectionName(),
                    aliasName);
            return true;
        } catch (Exception e) {
            LOG.error("SolrIndexAliasRegister has error:", e);
        }

        return false;
    }


}
